package unimelb.filesync.source;

import java.io.File;
import java.util.TimerTask;

import filesync.SynchronisedFile;

public class FileChangeMonitorTask extends TimerTask {

    private SynchronisedFile syncFile;

    private File file;

    private long lastModified;

    private boolean firstRun;

    public FileChangeMonitorTask(SynchronisedFile syncFile) {
        super();
        this.syncFile = syncFile;
        this.file = new File(syncFile.getFilename());
        this.lastModified = file.lastModified();
        this.firstRun = true;
    }

    @Override
    public void run() {
        if (firstRun) {
            try {
                syncFile.CheckFileState();
                firstRun = false;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        final long newModified = file.lastModified();
        if (lastModified != newModified) {
            lastModified = newModified;
            try {
                syncFile.CheckFileState();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
